package com.kevin.Code.Stack;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author Vinlee Xiao
 * @Classname SimplifyPath
 * @Description Leetcode 71 简化路径 个人觉得比较简单
 * @Date 2022/1/2 21:15
 * @Version 1.0
 */
public class SimplifyPath {

    /**
     * 思路:栈
     *
     * @param path
     * @return
     */
    public String simplifyPath(String path) {

        int len = path.length();

        if (len == 0) {
            return null;
        }
        //
        ArrayDeque<String> queue = new ArrayDeque<>();
        String[] split = path.split("/");
        for (int i = 0; i < split.length; i++) {
            if (split[i].equals("") || split[i].equals(".")) {
                continue;
            }
            //出栈
            if (split[i].equals("..")) {
                if (queue.size() > 0) {
                    queue.pollLast();
                }

            } else {
                queue.add("/" + split[i]);
            }
        }

        if (queue.size() == 0) {
            return new String("/");
        }

        //将栈中的每段路径转化成字符串
        StringBuilder builder = new StringBuilder();
        while (!queue.isEmpty()) {
            String s = queue.pollFirst();
            builder.append(s);
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        String str = "/../../";

        SimplifyPath simplifyPath = new SimplifyPath();
        String s = simplifyPath.simplifyPath(str);
        System.out.println(s);
//        String[] split = str.split("/");
//        System.out.println(split.length);
//        for (int i = 0; i < split.length; i++) {
//            System.out.println(i + 1 + "__ " + split[i]);
//        }
    }
}
